using System;
using System.Collections.Generic;
using System.Text;

namespace GoogleCalendarReminder
{
    /// <summary>
    /// A class which subscribes to a GoogleCalendarReminder.EventService and contains a collection of
    /// events that have occured and allows for the modification of these events.
    /// </summary>
    public class EventServiceSubscriber
    {
        #region Private Data Members

        private EventService _service;
        private EventEntryWrapperCollection _eventCollection;
        private Comparison<EventEntryWrapper> _comparison;

        #endregion

        #region Private Functions

        /// <summary>
        /// Adds events to the collection.
        /// </summary>
        private void _service_EventOccured(object sender, EventEntryWrapperEventArgs e)
        {
            _eventCollection.Add(e.Event);
            _eventCollection.Sort(_comparison);
        }

        /// <summary>
        /// Provides a method of comparison for two GoogleCalendarReminder.EventEntryWrapper objects.
        /// </summary>
        private int compare(EventEntryWrapper l, EventEntryWrapper r)
        {
            return l.Times[0].StartTime.CompareTo(r.Times[0].StartTime);
        }

        #endregion

        #region Constructors

        /// <summary>
        /// Creates a new instance of the GoogleCalendarReminder.EventServiceSubscriber class.
        /// </summary>
        /// <param name="service">The service to subscribe to.</param>
        /// <exception cref="System.ArgumentNullException">Parameters can't be null.</exception>
        public EventServiceSubscriber(EventService service)
        {
            if (service == null)
                throw new ArgumentNullException("Parameters can't be null.");

            _eventCollection = new EventEntryWrapperCollection();

            _comparison = new Comparison<EventEntryWrapper>(compare);

            _service = service;
            _service.EventOccured += 
                new EventHandler<EventEntryWrapperEventArgs>(_service_EventOccured);
        }

        #endregion

        #region Public Properties

        /// <summary>
        /// Gets the collection of events.
        /// </summary>
        public EventEntryWrapperCollection Events
        {
            get { return _eventCollection; }
        }

        #endregion
    }
}
